package cn.wen.base.decoration;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import cn.wen.base.R;

/**
 * 使用LinearLayoutManager的分割线
 */

public class LinearItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public LinearItemDecoration(Context context, int drawableResId) {
        mDivider = ContextCompat.getDrawable(context, drawableResId);
    }
    public LinearItemDecoration(Context context) {
        this(context, R.drawable.decoration_list);
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 获取Item的位置
        int position = parent.getChildLayoutPosition(view);
        // 留出空间来画分割线
        if (position != 0) {
            outRect.top = mDivider.getIntrinsicHeight();
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        // 循环画分割线
        int childCount = parent.getChildCount();
        Rect rect = new Rect();
        rect.left = parent.getPaddingLeft();
        rect.right = parent.getWidth() - parent.getPaddingRight();
        for (int i = 1; i < childCount; i++) {
            View child = parent.getChildAt(i);
            rect.bottom = child.getTop();
            rect.top = rect.bottom - mDivider.getIntrinsicHeight();
            mDivider.setBounds(rect);
            mDivider.draw(c);
        }
    }
}
